#include <iostream>       // std::cout
#include <chrono>         // std::chrono::milliseconds
#include <thread>         // std::thread
#include <mutex>          // std::timed_mutex

std::timed_mutex mtx;

// mutex lock/unlock 及 lock_guard 省略

void fireworks () {
    // waiting to get a lock: each thread prints "-" every 200ms:
    // 最多wait 100 毫秒
    while (!mtx.try_lock_for(std::chrono::milliseconds(100))) {
        std::cout << "-";
    }
    // got a lock! - wait for 1s, then this thread prints "*"
    std::this_thread::sleep_for(std::chrono::milliseconds(1));
    std::cout << "*\n";
    mtx.unlock();
}
      
int main ()
{
    int thread_num = 10;
    std::thread threads[thread_num];
    // spawn 10 threads:
    for (int i=0; i<thread_num; ++i)
        threads[i] = std::thread(fireworks);
    for (auto& th : threads)
        th.join();

    return 0;
}
